package com.ruoyi.web.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;

@Configuration
public class AsyncConfig {
    @Value("${asyncThreadPool.pdfSignPool.corePoolSize}")
    private int corePoolSize;

    @Value("${asyncThreadPool.pdfSignPool.maxPoolSize}")
    private int maxPoolSize;

    @Value("${asyncThreadPool.pdfSignPool.queueCapacity}")
    private int queueCapacity;

    @Value("${asyncThreadPool.pdfSignPool.keepAliveSeconds}")
    private int keepAliveSeconds;

    @Value("${asyncThreadPool.pdfSignPool.threadNamePrefix}")
    private String threadNamePrefix;

    /**
     * 1.当线程池小于corePoolSize时，新提交任务将创建一个新线程执行任务，即使此时线程池中存在空闲线程。
     * 2.当线程池达到corePoolSize时，新提交任务将被放入workQueue中，等待线程池中任务调度执行
     * 3.当workQueue已满，且maximumPoolSize>corePoolSize时，新提交任务会创建新线程执行任务
     * 4.当提交任务数超过maximumPoolSize时，新提交任务由RejectedExecutionHandler处理
     * 5.当线程池中超过corePoolSize线程，空闲时间达到keepAliveTime时，关闭空闲线程
     * 6.当设置allowCoreThreadTimeOut(true)时，线程池中corePoolSize线程空闲时间达到keepAliveTime也将关闭
     */
    @Bean
    public Executor asyncExecutor() {
        ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
        //配置核心线程数
        threadPoolTaskExecutor.setCorePoolSize(corePoolSize);
        //配置最大线程数
        threadPoolTaskExecutor.setMaxPoolSize(maxPoolSize);
        //配置队列大小
        threadPoolTaskExecutor.setQueueCapacity(queueCapacity);
        //配置线程空闲时间
        threadPoolTaskExecutor.setKeepAliveSeconds(keepAliveSeconds);
        //配置线程池中的线程的名称前缀
        threadPoolTaskExecutor.setThreadNamePrefix(threadNamePrefix);
        // 设置拒绝策略：当pool已经达到max size的时候，如何处理新任务
        // CALLER_RUNS：不在新线程中执行任务，而是有调用者所在的线程来执行
//        threadPoolTaskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        threadPoolTaskExecutor.initialize();
        return threadPoolTaskExecutor;
    }
}